<script lang="ts" setup>
import { computed, ref } from 'vue'

import AdvancedTable from '@/components/sofastui/AdvancedTable/AdvancedTable.vue'
import AdvancedForm from '@/components/sofastui/AdvancedForm/AdvancedForm.vue'

import * as logConstant from './constant/log'
import * as templateConstant from './constant/template'
import * as firmConstant from './constant/firm'

const advancedFormRef = ref()
const advancedTableRef = ref()

const options = ref([
  {
    label: '邮箱日志',
    value: 'log',
  },
  {
    label: '邮箱模板',
    value: 'template',
  },
  {
    label: '邮箱厂商',
    value: 'firm',
  },
])
const active = ref(options.value[0].value)

// 表格字段
const fields = computed(() => {
  switch (active.value) {
    case 'log':
      return logConstant.fields
    case 'template':
      return templateConstant.fields
    case 'firm':
      return firmConstant.fields
    default:
      return []
  }
})

// 表格配置
const config = computed(() => {
  switch (active.value) {
    case 'log':
      return logConstant.config
    case 'template':
      return templateConstant.config
    case 'firm':
      return firmConstant.config
    default:
      return {}
  }
})

// 表单字段
const formRules = computed(() => {
  switch (active.value) {
    case 'log':
      return logConstant.formRules
    case 'template':
      return templateConstant.formRules
    case 'firm':
      return firmConstant.formRules
    default:
      return []
  }
})

const changeTab = (val: string) => {
  console.log(val)
}

// 创建
const handelAdd = () => {
  advancedFormRef.value?.show('add', {})
}

// 行展开
const handelRowExpand = (data: { [key: string]: unknown }) => {
  advancedFormRef.value?.show('update', data)
}

// 刷新表格数据
const refreshTableData = () => {
  advancedTableRef.value!.refresh()
}
</script>

<template>
  <LTab :options="options" v-model="active" @change="changeTab">
    <AdvancedTable
      :key="active"
      ref="advancedTableRef"
      :fields="fields"
      :config="config"
      @add="handelAdd"
      @rowExpand="handelRowExpand"
    >
    </AdvancedTable>
  </LTab>

  <!-- 修改表单 -->
  <AdvancedForm
    :key="active"
    ref="advancedFormRef"
    :config="config"
    :rule="formRules"
    @success="refreshTableData"
  />
</template>
